// pages/new_classify/index.js
import {
  getCategoryList,
  getProductslist,
  getProductDetail,
  postCartAdd,
  categoryindex
} from '../../api/store.js';
import {
  setFormId
} from '../../api/api.js';
import {
  getCartList,
  changeCartNum,
  cartDel,
  getCartCounts
} from '../../api/order.js';

const app = getApp();
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    parameter: {
      'navbar': '1',
      'return': '0',
      'title': '分类'
    },
    info:8,
    infoa:3,
    active_child:0,
    news:true,
    add_num:0,
    active_type:0,
    active: 0,
    scrollLeft: 0,
    category: [],
    navActive: 0,
    categoryTwo: [],
    productList: [],
    loadend: false,
    loading: false,
    loadTitle: '加载更多',
    where: {
      page: 1,
      limit: 20,
      keyword: "",
      cid: 0, //一级分类id
      sid: 0, //二级分类id
      news: 0,
      priceOrder: "",
      salesOrder: "",
      type: 1,
      store_id: wx.getStorageSync('store_id')
    },
    price: 0,
    stock: 0,
    nows: false,
    gradeSwitch: 1,
    attr: {
      activeAttr: false,
      productAttr: [],
      productSelect: {}
    },
    productValue: [],
    storeInfo: {},
    attrValue: "",
    id: 0, //产品id；
    cart: {
      CartCount: 0,
      animated: false,
      cartList: [],
      countmoney: 0,
      iShidden: true
    },
    navH: "",
    iShidden: true,
    isAuto: false,
    isNewOpen: true,
    invalidNum: 0,
    isClone:false,
    store_id:0,
    cindex:null,//从首页传过来的分类索引
    cgoodsid:null,//从首页传过来的分类id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    console.log(e)
    this.setData({
      navH: app.globalData.navHeight,
      cindex:e.index,
      cgoodsid:e.id
    })
    this.getCartList();
  },
  onLoadFun: function() {
    this.getCartList();
    this.getCategoryData();
  },
  getCartList: function() {
    var that = this;
    if (!app.globalData.isLog) {
      this.setData({
        iShidden: false
      });
    } else {
      that.store_id = wx.getStorageSync('store_id');
      getCartList({shid:that.store_id}).then(res => {
        var cartNum = 0;
        var invalid = res.data.invalid;
        for (var i = 0; i < invalid.length; i++) {
          cartNum = cartNum + invalid[i].cart_num;
        }
        that.setData({
          'cart.cartList': res.data.valid,
          invalidNum: cartNum
        })
        that.countMoney();
      });
    }
  },
   //  产品列表 加 的点击事件；
   productPlus: function(e) {
    var that = this,
      listw = that.data.productList,
      index = e.currentTarget.dataset.index;
    that.setData({
      id: listw[index].id,
      'cart.iShidden': true
    })
    if (listw[index].cart_num >= listw[index].stock) return false;
    that.goCat(index, listw);
  },
  //产品列表 加 的功能；
  publicPlus: function(index, listw) {
    listw[index].cart_num++;
    if (listw[index].cart_num >= listw[index].stock) {
      listw[index].cart_num = listw[index].stock;
    }
    this.setData({
      productList: listw
    })
  },
  //  产品列表 减 的点击事件；
  productReduce: function(e) {
    let that = this,
      listw = that.data.productList,
      index = e.currentTarget.dataset.index,
      id = listw[index].id;
    that.data.cart.cartList.forEach(function(item, i) {
      if (id == item.product_id) {
        that.reduce(i);
      }
    });
  },
  //产品列表 减 的功能；
  publicReduce: function(index, listw) {
    listw[index].cart_num--;
    if (listw[index].cart_num <= 1) {
      listw[index].cart_num = 1;
    }
    this.setData({
      productList: listw
    })
  },
  // 加入购物车；
  goCat: function(index, listw) {
    var that = this;
    var q = {
      productId: that.data.id,
      cartNum: 1,
      new: 0,
      uniqueId: that.data.attr.productSelect !== undefined ?
        that.data.attr.productSelect.unique :
        ""
    };
    postCartAdd(q) .then(res => {
      console.log(res)

        that.getCartCount(true);
        that.getCartList();
        if (index != undefined) {
          that.publicPlus(index, listw);
        }
      })
      .catch(res => {
        // console.log(res)
        // wx.showToast({
        //   title:res,
        // })
        app.Tips({
          title: res
        });
      });
  },
  //获取购物车数量
  getCartCount: function(isAnima) {
    var that = this;
    if (!app.globalData.isLog) {
      this.setData({
        iShidden: false
      });
    } else {
      getCartCounts({
        numType: 0
      }).then(res => {
        that.setData({
          'cart.CartCount': res.data.count - that.data.invalidNum
        })
        if (isAnima) {
          that.setData({
            'cart.animated': true
          })
          setTimeout(function() {
            that.setData({
              'cart.animated': false
            })
          }, 500);
        }
      });
    }
  },
  getCategoryData: function() {
    var that = this;
    that.store_id = wx.getStorageSync('store_id');
    //console.log(that.store_id);
    getCategoryList({store_id:that.store_id,shid:that.store_id}).then(res => {
      console.log(res.data);
      that.setData({
        category: res.data,
        scrollLeft: (that.data.active - 1) * 60
      })

      console.log(that.data.where.cid)
      // if (that.data.where.cid) {
        // console.log(that.data.cindex)
        if(that.data.cindex==null){
          that.setData({
            active: 0,
            navActive: 0
          })
        }else{
          that.setData({
            active: that.data.cindex,
            navActive: 0
          })
        }

        console.log(that.data.active)
        console.log(res.data[that.data.active].children)
        if (res.data[that.data.active].children.length) {
          that.data.where.sid = res.data[that.data.active].children[0].id
        } else {
          that.data.where.sid = ""
        }
        that.setData({
          'where.cid': that.data.where.cid,
          categoryTwo: res.data[that.data.active].children,
          'where.sid': that.data.where.sid
        })
        that.setData({
          loadend: false,
          loading: false,
          ['where.page']: 1
        });
        that.getGoodlist(true);
         that.getCartCount();

    });
  },
  getGoodlist: function(isPage) {
    var that = this;
    that.setWhere();
    if (that.data.loadend) return;
    if (that.data.loading) return;
    if (isPage === true) that.setData({
      productList: []
    });
    that.setData({
      loading: true,
      loadTitle: '',
     ['where.shid']:wx.getStorageSync('store_id')
    });
    console.log(that.data.where);
    console.log('产品列表')
    
    getProductslist(that.data.where).then(res => {
      console.log(res)
      var list = res.data;
      var productList = app.SplitArray(list, that.data.productList);
      var loadend = list.length < that.data.where.limit;
      that.setData({
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '加载更多',
        productList: productList,
        ['where.page']: that.data.where.page + 1,
        shid:wx.getStorageSync('store_id')
      });
    }).catch(err => {
      that.setData({
        loading: false,
        loadTitle: '加载更多'
      });
    });
  },
  oneSortTap: function(e) {
    var index = e.currentTarget.dataset.id;
    this.setData({
      active: index,
      navActive: 0,
      categoryTwo: this.data.category[index].children,
      'where.cid': this.data.category[index].id,
      'where.page': 1,
      loadend: false,
      loading: false
    })
    if (this.data.active > 2) {
      this.setData({
        scrollLeft: (e.currentTarget.dataset.id) * 60
      })
    }
    if (this.data.categoryTwo.length) {
      this.setData({
        'where.sid': this.data.categoryTwo[0].id
      })
    } else {
      this.setData({
        'where.sid': 0
      })
    }
    this.getGoodlist(true);
  },
  twoSortTap: function(e) {
    var index = e.currentTarget.dataset.index;
    console.log(index)
    this.setData({
      navActive: index,
      'where.cid': this.data.category[this.data.active].id,
      'where.sid': this.data.categoryTwo[index].id,
      'where.page': 1,
      loadend: false,
      loading: false
    })
    this.getGoodlist(true);
  },
  reduce: function(index) {
    var index;
    if (index instanceof Object) {
      index = index.detail;
      this.setData({
        "cart.iShidden": false
      })
    } else {
      index = index;
      this.setData({
        "cart.iShidden": true
      })
    }
    var that = this;
    var list = that.data.cart.cartList[index],
      productId = list.product_id;
    that.productId(list, 0);
    list.cart_num--;
    if (list.cart_num < 1) {
      cartDel([list.id]).then(function() {
        console.log(123)
        that.data.cart.cartList.splice(index, 1);
        that.setData({
          'cart.cartList': that.data.cart.cartList
        })
        that.data.productList.forEach(function(item, index) {
          if (productId == item.id) {
            that.data.productList[index].cart_num = 0;
            that.setData({
              productList: that.data.productList
            })
          }
        });
        if (that.data.cart.cartList.length < 1) {
          that.setData({
            'cart.iShidden': true
          })
        }
      });
    }
    that.setData({
      'cart.cartList': that.data.cart.cartList
    })
    that.countMoney();
    that.syncCartNum(list);
  },
  //加
  plus: function(e) {
    var that = this;
    var list = that.data.cart.cartList[e.detail];
    that.productId(list, 1);
    list.cart_num++;
    if (list.productInfo.attrInfo) {
      if (list.cart_num >= list.productInfo.attrInfo.stock) {
        list.cart_num = list.productInfo.attrInfo.stock;
      }
    } else {
      if (list.cart_num >= list.productInfo.stock) {
        list.cart_num = list.productInfo.stock;
      }
    }
    that.setData({
      'cart.cartList': that.data.cart.cartList,
      "cart.iShidden": false
    })
    that.countMoney();
    that.syncCartNum(list);
  },
  //获取当前购物车在产品列表对应id的index值；
  productId: function(list, status) {
    let that = this;
    let id = list.product_id;
    let listw = that.data.productList;
    listw.forEach(function(item, i) {
      if (id == item.id) {
        if (status) {
          that.publicPlus(i, listw);
        } else {
          that.publicReduce(i, listw);
        }
      }
    });
  },
  //  修改购物车数量；
  syncCartNum(cart) {
    changeCartNum(cart.id, Math.max(cart.cart_num, 1) || 1).then(() => {
      this.getCartCount();
    });
  },
  //总共价钱；
  countMoney: function() {
    var that = this;
    var carmoney = 0;
    var array = that.data.cart.cartList;
    for (var i = 0; i < array.length; i++) {
      carmoney = util.$h.Add(carmoney, util.$h.Mul(array[i].cart_num, array[i].truePrice));
    }
    that.setData({
      'cart.countmoney': carmoney
    })
  },
  delGood: function() {
    let that = this,
      id = [],
      productId = [],
      listw = that.data.productList,
      list = that.data.cart.cartList;
    list.forEach(function(val) {
      id.push(val.id);
      productId.push(val.product_id);
    });
    cartDel(id).then(function() {
      list.splice(0, list.length);
      that.setData({
        'cart.cartList': list
      })
      that.countMoney();
      that.getCartCount();
      that.setData({
        'cart.iShidden': true
      })
      listw.forEach(function(item, index) {
        productId.forEach(function(itemId) {
          if (item.id == itemId) {
            listw[index].cart_num = 0;
            that.setData({
              productList: listw
            })
          }
        });
      });
    });
  },
  myattr: function(e) {
    this.setData({
      "attr.activeAttr": e.detail,
      "attr.productSelect": []
    })
  },
  settlement: function(e) {
    var that = this,
      formId = e.detail;
    if (app.globalData.isLog === false)
      this.setData({
        iShidden: false
      })
    else {
      setFormId(formId);
      var list = that.data.cart.cartList,
        id = [];
      list.forEach(function(val) {
        id.push(val.id);
      });
      if (id.length > 0) {
        wx.navigateTo({
          url: '/pages/order_confirm/index?cartId=' + id.join(',')
        });
      } else {
        return app.Tips({
          title: '请选择产品'
        });
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.navWord) {
      console.log(app.navWord)
      this.setData({
        'where.cid': app.navWord
      });
    }
    if (this.data.isClone) {
      if (this.data.isNewOpen) {
        this.getCategoryData();
      }
      this.getCartList();
      this.getCartCount();
    }
  },
 //点击事件处理
 set_where: function(e) {
  var dataset = e.target.dataset;
  switch (dataset.type) {
    case '1':
      if (this.data.price == 0)
        this.data.price = 1;
      else if (this.data.price == 1)
        this.data.price = 2;
      else if (this.data.price == 2)
        this.data.price = 0;
      this.setData({
        price: this.data.price,
        stock: 0
      });
      break;
    case '2':
      if (this.data.stock == 0)
        this.data.stock = 1;
      else if (this.data.stock == 1)
        this.data.stock = 2;
      else if (this.data.stock == 2)
        this.data.stock = 0;
      this.setData({
        stock: this.data.stock,
        price: 0
      });
      break;
    case '3':
      this.setData({
        nows: !this.data.nows
      });
      break;
  }
  this.setData({
    loadend: false,
    loading: false,
    ['where.page']: 1,
    gradeSwitch: dataset.type,
    shid:wx.getStorageSync('store_id')
  });
  this.getGoodlist(true);
},
//设置where条件
setWhere: function() {
  if (this.data.price == 0)
    this.data.where.priceOrder = '';
  else if (this.data.price == 1)
    this.data.where.priceOrder = 'desc';
  else if (this.data.price == 2)
    this.data.where.priceOrder = 'asc';
  if (this.data.stock == 0)
    this.data.where.salesOrder = '';
  else if (this.data.stock == 1)
    this.data.where.salesOrder = 'desc';
  else if (this.data.stock == 2)
    this.data.where.salesOrder = 'asc';
  this.data.where.news = this.data.nows ? 1 : 0;
  this.setData({
    where: this.data.where
  });
},
  //总共价钱；
  countMoney: function() {
    var that = this;
    var carmoney = 0;
    var array = that.data.cart.cartList;
    for (var i = 0; i < array.length; i++) {
      carmoney = util.$h.Add(carmoney, util.$h.Mul(array[i].cart_num, array[i].truePrice));
    }
    that.setData({
      'cart.countmoney': carmoney
    })
  },
gaPeg:function(e){
  var url = e.currentTarget.dataset.url;
  wx.navigateTo({
    url
  })
},
gaPeg:function(e){
  var url = e.currentTarget.dataset.url;
  wx.navigateTo({
    url
  })
},
goDetail: function(e) {
  this.setData({
    isNewOpen: false
  })
  var index = e.currentTarget.dataset.index;
  wx.navigateTo({
    url: '/pages/goods_details/index?id=' + this.data.productList[index].id
  });
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({ isClone: true });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})